package com.bangdao.auxiliary;

/**
 * @author chen
 * @create 2021-01-06
 */

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 6个同学陆续离开教室后值班同学才可以关门
 * main方法也是一个进程，在这里是主进程，即上锁的同学
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //创建计数器对象
        CountDownLatch downLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    // 每个同学墨迹几秒钟
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() + "同学出门了");
                    // 调用countDown()计算减1
                    downLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
        // 调用计算器的await方法，等待6位同学都出来
        downLatch.await();
        System.out.println("值班同学锁门了");
    }
}

